package cn.accjiyun.controller.webbackend;

import cn.accjiyun.core.controller.BaseController;
import cn.accjiyun.core.entity.PageModel;
import cn.accjiyun.core.utils.SingletonLoginUtils;
import cn.accjiyun.core.utils.WebUtils;
import cn.accjiyun.model.article.QueryArticle;
import cn.accjiyun.model.system.LoginLog;
import cn.accjiyun.model.system.SysUser;
import cn.accjiyun.service.ArticleService;
import cn.accjiyun.service.LibraryService;
import cn.accjiyun.service.LoginLogService;
import cn.accjiyun.service.SysUserService;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * Created by jiyun on 2017/2/5.
 */
@Controller
@RequestMapping("/admin")
public class MainController extends BaseController {
    private static final Logger logger = LoggerFactory.getLogger(MainController.class);
    private static String mainPage = getViewPath("/admin//main/main");//后台管理主界面
    private static String mainIndexPage = getViewPath("/admin/main/welcome");//后台操作中心初始化首页
    private static String loginFail = "redirect:/admin/main/loginFail";//后台管理主界面

    @Autowired
    private ArticleService articleService;
    @Autowired
    private LibraryService libraryService;
    @Autowired
    private LoginLogService loginLogService;
    @Autowired
    private SysUserService sysUserService;

    /**
     * 进入操作中心
     *
     * @param request
     * @return ModelAndView
     */
    @RequestMapping("/main/main")
    public ModelAndView mainPage(HttpServletRequest request) {
        ModelAndView model = new ModelAndView();
        try {
            SysUser sysuser = SingletonLoginUtils.getLoginSysUser(request);
            if (sysuser != null) {
                model.setViewName(mainPage);
                model.addObject("sysUser", sysuser);
            } else {
                model.setViewName(loginFail);
            }
        } catch (Exception e) {
            model.setViewName(this.setExceptionRequest(request, e));
            logger.error("mainPage()--error", e);
        }
        return model;
    }

    /**
     * 后台操作中心初始化首页
     *
     * @param request
     * @return ModelAndView
     */
    @RequestMapping("/main/welcome")
    public ModelAndView mainIndex(HttpServletRequest request) {
        ModelAndView model = new ModelAndView();
        try {
            model.setViewName(mainIndexPage);
            model.addObject("articleNum", articleService.queryAllArticleCount());
            model.addObject("libraryNum", libraryService.queryAllLibraryCount());
        } catch (Exception e) {
            model.setViewName(this.setExceptionRequest(request, e));
            logger.error("mainIndex()---error", e);
        }
        return model;
    }

    /**
     * 访问权限受限制跳转
     *
     * @return ModelAndView
     */
    @RequestMapping("/loginFail")
    public ModelAndView notFunctionMsg() {
        ModelAndView model = new ModelAndView();
        model.addObject("message", "对不起，您没有操作权限！");
        model.setViewName("/common/notFunctonMsg");
        return model;
    }

    @RequestMapping("/getLoginLogList")
    @ResponseBody
    public String getLoginLogList(HttpServletRequest request) {
        JsonObject resultJson = new JsonObject();
        try {
            QueryArticle queryArticle = new QueryArticle();
            String pageNoString = request.getParameter("pageNo");
            if (!WebUtils.isValidateRealString(pageNoString) || !WebUtils.isNumeric(pageNoString)) {
                resultJson.addProperty("status", 400);
                resultJson.addProperty("msg", "数据输入不合法！");
                return gson.toJson(resultJson);
            }
            PageModel<LoginLog> page = new PageModel<>();
            page.setPageSize(8);
            page.setPageNo(Integer.valueOf(pageNoString));
            List<LoginLog> loginLogList = loginLogService.queryLoginLogPage(queryArticle, page);
            JsonArray array = new JsonArray();
            for (LoginLog loginLog : loginLogList) {
                JsonObject list = new JsonObject();
                list.addProperty("loginId", loginLog.getLoginId());
                list.addProperty("loginName", sysUserService.querySysUserByUserId(loginLog.getUserId()).getLoginName());
                list.addProperty("loginTime", WebUtils.timestampToString(loginLog.getLoginTime()));
                list.addProperty("ipAddress", loginLog.getIpAddress());
                array.add(list);
            }
            JsonObject list = new JsonObject();
            list.add("list", array);
            resultJson.addProperty("status", 200);
            resultJson.addProperty("pages", page.getTotalPageSize());
            resultJson.add("data", list);
        } catch (Exception e) {
            logger.error("AdminArticleController.showArticleList()--error", e);
            resultJson.addProperty("status", 400);
            resultJson.addProperty("msg", "获取列表失败！");
        }
        logger.info(gson.toJson(resultJson));
        return gson.toJson(resultJson);
    }

}
